package com.twu.biblioteca.presenter;

import com.twu.biblioteca.events.HasEventListener;
import com.twu.biblioteca.events.Listener;
import com.twu.biblioteca.model.item.exceptions.InexistantItemException;
import com.twu.biblioteca.model.menu.IMenu;
import com.twu.biblioteca.model.menu.Menu;
import com.twu.biblioteca.model.menu.MenuFormatter;
import com.twu.biblioteca.model.session.Session;
import com.twu.biblioteca.model.session.SessionManager;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 08/08/2013
 * Time: 10:42
 * To change this template use File | Settings | File Templates.
 */
public class MenuPresenter implements Presenter{

    public interface Display extends HasEventListener{
        void init(MenuFormatter menuFormatter);
        int getUserSelection();
        void warnInvalidInput();
    }

    private final Display view;
    private final SessionManager sessionManager;
    private final Menu menu;

    private boolean validSession;
    private Session session;

    public MenuPresenter(Display view, SessionManager sessionManager, Menu menu) {
        this.view = view;
        this.menu = menu;
        this.sessionManager = sessionManager;
        bind();
    }

    @Override
    public void go(Session session) {
        this.session = session;
        MenuFormatter menuFormatter = new MenuFormatter();

        validSession = sessionManager.isValid(session);

        if (validSession){
            menu.formatPrivateList(menuFormatter);
        }  else {
            menu.formatPublicList(menuFormatter);
        }

        view.init(menuFormatter);
    }

    private void bind(){
        view.addEventListener(new Listener() {
            @Override
            public void onEvent() {
                handleMenuSelection(session);
            }
        });
    }

    void handleMenuSelection(Session session) {
        try{
            int selection = view.getUserSelection();
            IMenu item;

            if (validSession){
                item = menu.getPrivateItem(selection);
            } else {
                item = menu.getPublicItem(selection);
            }

            item.execute(session);

        } catch (InexistantItemException e) {
            view.warnInvalidInput();
        }
    }

}